#include "settings.h"
#include <iostream>
#include <DListView>
using namespace std;
Settings::Settings(QObject *parent) : QObject(parent)
{

}

QJsonObject Settings::getObject()
{
    QJsonObject obj_settings;
    QJsonDocument doc_settings;
    QDir dir;
    dir.mkdir(setting_path);
    QFile file(setting_file);
    file.open(QFile::ReadWrite);
    QByteArray bty=file.readAll();
//    cout<<bty.toStdString();
    doc_settings=QJsonDocument::fromJson(bty);
    obj_settings = doc_settings.object();
    file.close();
    return obj_settings;
}

bool Settings::setValue(QString key, QString value)
{
    QJsonObject obj_settings;
    QJsonDocument doc_settings;
    obj_settings = getObject();
    obj_settings.insert(key,value);
    doc_settings.setObject(obj_settings);
    WSettingFile(doc_settings.toJson());
    return true;
}

QString Settings::getValue(QString key)
{
    QJsonObject obj_settings;
    obj_settings = getObject();
//    cout<<key.toStdString()<<":"<<obj_settings.value(key).toString().toStdString();
    return  obj_settings.value(key).toString();
}

bool Settings::WSettingFile(QByteArray bty)
{
    QDir dir;
    dir.mkdir(setting_path);
    QFile file(setting_file);
    file.open(QFile::WriteOnly|QFile::Truncate);
    file.close();
    file.open(QFile::WriteOnly);
    if(file.write(bty)){
        file.close();
        return true;
    }
    file.close();
    return false;

}
